package com.taptech.doufu.ui.activity;

import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;

import com.alibaba.fastjson.JSON;
import com.taptech.doufu.R;
import com.taptech.doufu.ui.activity.base.DiaobaoBaseActivity;
import com.taptech.doufu.ui.adapter.NovelVerticalCoverAdapter;
import com.taptech.doufu.ui.adapter.TTHomeNovelAdapter;
import com.taptech.doufu.app.WeMediaApplication;
import com.taptech.doufu.manager.UserLogManager;
import com.taptech.doufu.bean.HomeTopBean;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.listener.HttpResponseListener;
import com.taptech.doufu.bean.MoreNovelBean;
import com.taptech.doufu.services.HomeMainServices;
import com.taptech.doufu.util.DiaobaoUtil;
import com.taptech.doufu.util.StartActivityUtil;
import com.taptech.doufu.util.UIUtil;
import com.taptech.doufu.net.httputils.HttpResponseObject;
import com.taptech.doufu.ui.view.PullToRefreshListView;
import com.taptech.doufu.ui.view.TitleTextView;
import com.taptech.doufu.ui.view.WaitDialog;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

/**
 * Created by longsiyang on 16/4/22.
 */
public class MoreNovel2Activity extends DiaobaoBaseActivity implements HttpResponseListener, GestureDetector.OnGestureListener, GestureDetector.OnDoubleTapListener {
    PullToRefreshListView moreListView;
    TitleTextView moreTitle;
    WaitDialog dialog;
    private NovelVerticalCoverAdapter verticalCoverAdapter;
    private List<HomeTopBean> beanList;
    // UI控制
    private String last = "";
    private int page = 1;
    private boolean hasMoreContent = false;
    private boolean isFromHome = false;
    private String url = "";
    private String title;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_more_recomment_layout);
        isFromHome = getIntent().getBooleanExtra("IS_FROMHOME", false);
        moreListView = (PullToRefreshListView) findViewById(R.id.activity_more_recomment_list);
        moreListView.setRefreshable(true);
        moreListView.setLoadmoreable(true);
            verticalCoverAdapter = new NovelVerticalCoverAdapter(this);
            moreListView.setAdapter(verticalCoverAdapter);
        moreTitle = (TitleTextView) findViewById(R.id.activity_more_recomment_title);
        url = getIntent().getStringExtra(Constant.URL);
        title = getIntent().getStringExtra(Constant.TITLE);
        moreTitle.setText(title);
        moreListView.setOnLoadAndRefreshListener(new PullToRefreshListView.OnLoadAndRefreshListener() {

            @Override
            public void onRefresh() {
                loadDate();
            }

            @Override
            public void loadMore() {
                // TODO Auto-generated method stub

            }
        });
        moreListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // TODO Auto-generated method stub
                if (beanList != null && beanList.size() >= id) {
                    HomeTopBean bean = beanList.get((int) id);
                    String prePage;
                    String type = ((WeMediaApplication) (WeMediaApplication.applicationContext)).sexType;
                    if ("1".equals(type)) {//彩虹
                        prePage = "rainbow-"+title;
                    } else if ("3".equals(type)) {
                        prePage = "romance-"+title;
                    }else {
                        prePage = title;
                    }
                    UserLogManager.addLog(UserLogManager.LOG_EVENT_NAME_NOVEL_DETAIL,
                            bean.getId(),"",prePage,"TFNovelDetail.js");

                    StartActivityUtil.novelOnclick(MoreNovel2Activity.this, bean.getId());
                }

            }
        });
        moreListView.setLoadmoreable(true);
        moreListView.setOnScrollToBottomListener(new PullToRefreshListView.OnScrollToBottomListener() {
            @Override
            public void OnScrollToBottom() {
                loadMoreData();
            }
        });
        dialog = new WaitDialog(this, R.style.updateDialog);
        //dialog.show();
        moreTitle.enableGesture(true);
        loadDate();
    }

    private void loadDate() {
        last = "";
        page = 1;
        if (isFromHome) {
            HomeMainServices.getInstance().getMoreNovel(url, this, last,page,HomeMainServices.HANDLE_TYPE_REFRESH_RECOMMEND_NOVEL);
        }
    }

    @Override
    public void handleResponse(int handleType, HttpResponseObject response) {
        // TODO Auto-generated method stub
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
        if (response == null) {
            UIUtil.toastMessage(this, Constant.loadingFail);
            return;
        }
        moreListView.onRefreshComplete();
        moreListView.loadMoreComplete();
        if (response.getStatus() == 0 && response.getFail_code() == 0) {
            switch (handleType) {
                case HomeMainServices.HANDLE_TYPE_MORE_RECOMMEND_NOVEL:
                case HomeMainServices.HANDLE_TYPE_REFRESH_RECOMMEND_NOVEL:
                    JSONObject data = (JSONObject) response.getData();
                    try {
                        JSONArray dataArray = null;
                        if (data.has("list")) {
                            dataArray = data.getJSONArray("list");
                        } else if (data.has("novels")) {
                            Log.e("tag", "wufa");
                            dataArray = data.getJSONArray("novels");
                        } else if (data.has("items")) {
                            dataArray = data.getJSONArray("items");
                        }

                        if (dataArray != null && dataArray.length() > 0) {
                            hasMoreContent = true;
                            if (dataArray.length() >= 10) {
                                moreListView.setLoadmoreable(true);
                            }else{
                                moreListView.setLoadmoreable(false);
                            }
                            List<MoreNovelBean> list = JSON.parseArray(dataArray.toString(), MoreNovelBean.class);
                            if (handleType == HomeMainServices.HANDLE_TYPE_MORE_RECOMMEND_NOVEL) {
                                verticalCoverAdapter.addAll(list);
                            }else{
                                verticalCoverAdapter.setData(list);
                            }


                        }else{
                            moreListView.setLoadmoreable(false);
                            hasMoreContent = false;
                        }
                        if (data.has("last")) {
                            last = data.getString("last");
                        }
                        if (data.has("page")) {
                            page = data.getInt("page")+1;
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
            }
        } else {
            if (response.getUser_msg() != null) {
                UIUtil.toastMessage(this, response.getUser_msg());
            } else {
                UIUtil.toastMessage(this, Constant.loadingFail);
            }
        }
    }

    private synchronized void loadMoreData() {
        if (hasMoreContent) {
            hasMoreContent = false;
            HomeMainServices.getInstance().getMoreNovel(url, this, last,page,HomeMainServices.HANDLE_TYPE_MORE_RECOMMEND_NOVEL);
        }
    }

    public void back(View v) {
        finish();
    }

    GestureDetector gestureDetector;

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        //        gestureDetector.onTouchEvent(event);
        return false;
    }

    @Override
    public boolean onSingleTapConfirmed(MotionEvent motionEvent) {
        return false;
    }

    @Override
    public boolean onDoubleTap(MotionEvent motionEvent) {
        UIUtil.toastMessage(this, "你竟然发现了这里可以双击。。。");
        return true;
    }

    @Override
    public boolean onDoubleTapEvent(MotionEvent motionEvent) {
        return false;
    }

    @Override
    public boolean onDown(MotionEvent motionEvent) {
        return true;
    }

    @Override
    public void onShowPress(MotionEvent motionEvent) {

    }

    @Override
    public boolean onSingleTapUp(MotionEvent motionEvent) {
        return false;
    }

    @Override
    public boolean onScroll(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
        return false;
    }

    @Override
    public void onLongPress(MotionEvent motionEvent) {

    }

    @Override
    public boolean onFling(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
        return false;
    }
}
